import type {AxiosRequestConfig, AxiosInstance, InternalAxiosRequestConfig} from 'axios'
import axios from 'axios'

const instance: AxiosInstance = axios.create({
  baseURL: '/api',
  timeout: 5000,
})

export interface ResponseData<T = any> {
  code?: number
  data: T
  msg: string
}

export const whileList = [
  '/user/login',
  '/user/register'
]

// 添加请求拦截器
instance.interceptors.request.use((config: InternalAxiosRequestConfig) => {
  // 请求之前的相关处理
  // 添加名称为Bearer auth的请求头
  if (!whileList.includes(config.url as string)) {
    config.headers['Authorization'] = 'Bearer UwLTMlEwsFq1XJTCvBCxoa9qkemghPLAWpoPQF0GAuBkVvxDYxRnffpqnoNeyYKq'
  }

  return config;
}, error => {
  // 对请求错误做些什么
  return Promise.reject(error);
});

// 添加响应拦截器
instance.interceptors.response.use((response) => {
  // 对响应数据做点什么
  // 2xx 范围内的状态码都会触发该函数。
  const {msg, code} = response.data as ResponseData
  if (code === 200) {
    return response
  } else {
    return Promise.reject(msg)
  }
}, error => {
  // 超出 2xx 范围的状态码都会触发该函数。
  // 对响应错误做点什么
  return Promise.reject(error);
});


export const useGet = async <R = any, P = any>(url: string, params?: P, config?: AxiosRequestConfig): Promise<ResponseData<R>> => {
  if (params) {
    url += '?' + new URLSearchParams(params).toString()
  }
  const {data} = await instance.get<ResponseData<R>>(url, config)
  return data
}

export const usePost = async <R = any, P = any>(url: string, data?: P, config?: AxiosRequestConfig): Promise<ResponseData<R>> => {
  const {data: resData} = await instance.post<ResponseData<R>>(url, data, config)
  return resData
}


export const useDelete = async <R = any, P = any>(url: string, params?: P, config?: AxiosRequestConfig): Promise<ResponseData<R>> => {
  if (params) {
    url += '?' + new URLSearchParams(params).toString()
  }
  const {data: resData} = await instance.delete<ResponseData<R>>(url, config)
  return resData
}

export const usePut = async <R = any, P = any>(url: string, data?: P, config?: AxiosRequestConfig): Promise<ResponseData<R>> => {
  const {data: resData} = await instance.put<ResponseData<R>>(url, data, config)
  return resData
}

export default instance
